package com.mzba.easy.weibo.util;

import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.URLSpan;
import android.util.Log;
import android.widget.TextView;

/**
 * 处理TextView界面的类
 * 
 * @author 林乐鹏
 * @version 2011-06-23
 * 
 */
public class TextAutoLink {

	// 加入话题 好友 URL的连结
	public static char strarray[];

	public static void addURLSpan(String str, TextView textView) {
		SpannableString ss = new SpannableString(str);
		try {
			strarray = str.toCharArray();
			int l = str.length() - 10;
			int start = str.indexOf("http://");
			int end = 0;
			if (start != -1) {
				end = str.length();
				ss.setSpan(new URLSpan(str), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			}
			for (int i = 0; i < l; i++) {
				if (strarray[i] == 'h' && strarray[i + 1] == 't'
						&& strarray[i + 2] == 't' && strarray[i + 3] == 'p'
						&& strarray[i + 4] == ':' && strarray[i + 5] == '/'
						&& strarray[i + 6] == '/') {
					StringBuffer sb = new StringBuffer("http://");
					for (int j = i + 7; true; j++) {
						if (strarray[j] != ' ')
							sb.append(strarray[j]);
						else {
							Log.d("http", sb.toString());
							ss.setSpan(new URLSpan(sb.toString()), i, j, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
							i = j;
							break;
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			int l = str.length();
			StringBuffer sb = null;
			boolean start = false;
			int startIndex = 0;
			for (int i = 0; i < l; i++) {
				if (strarray[i] == '@') {
					start = true;
					sb = new StringBuffer("weibo://weibo.view/");
					startIndex = i;
				} else {
					if (start) {
						if (strarray[i] == ':') {
							ss.setSpan(new URLSpan(sb.toString()), startIndex, i,
									Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
							sb = null;
							start = false;
						} 
					}
				}

			}
			// 处理 话题
			start = false;
			startIndex = 0;
			for (int i = 0; i < l; i++) {
				if (strarray[i] == '#') {
					if (!start) {
						start = true;
						sb = new StringBuffer("weibo://weibo.view/");
						startIndex = i;
					} else {
						sb.append('#');
						ss.setSpan(new URLSpan(sb.toString()), startIndex, i + 1,
								Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
						sb = null;
						start = false;
					}
				} else {
					if (start) {
						sb.append(strarray[i]);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		textView.setText(ss);
		strarray = null;
	}
}
